<template>
  <BasicDrawer v-bind="$attrs" :showFooter="true" :okAuth="'mo:order:scOrder:edit'" @register="registerDrawer"
    @ok="handleSubmit" width="90%">
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #routeList>

        <BasicTable  @register="registerRouteDataChildTable" @row-click="handleRouteDataChildRowClick">
          <template #sortUp="{ record }">
            <a @click="clickUp(record)" style="padding: 8px">
              <Icon icon="ant-design:arrow-up-outlined" size="18" color="#efbd47" />
            </a>
            <a @click="clickDown(record)">
              <Icon icon="ant-design:arrow-down-outlined" size="18" color="#efbd47" />
            </a>
          </template>

          <template #checkBox="{ record, column }">
            <a-checkbox v-model:checked="record[column.dataIndex]" />
            <!-- {{record[column.dataIndex]}} -->
          </template>
        </BasicTable>
        <a-button class="mt-2" @click="handleBasMesRouteOperAdd" v-auth="'mes:orderRoute:edit'">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>

    <ListSelect selectType="basMesRouteSelect" :checkbox="true" :params="queryParams" :selectList="listSelectRef"
      ref="routeSelectRef" @select="handSelect" v-show="false" />
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsBasM8OrderRouteForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  // import { M8OrderRoute, m8OrderRouteSave, m8OrderRouteForm, signCheck } from '/@/api/bas/m8OrderRoute';
  import { basMesOperTreeData } from '/@/api/bas/mes/oper/basMesOper';
  import { MesOrderRoute, mesOrderRouteSaveRoute } from '/@/api/mes/mo/route/mesOrderRoute';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register', 'closeModal', 'openDrawer']);

  const { t } = useI18n('bas.m8OrderRoute');
  const { showMessage } = useMessage();
  const record = ref < MesOrderRoute > ({} as MesOrderRoute);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: t('工艺编辑'),
  }));

  

  let listSelectRef = ref([]);
  let queryParams = ref({});
  let routeSelectRef = ref < any > (null);

  const inputFormSchemas: FormSchema[] = [
    // {
    //   label: t('订单ID'),
    //   field: 'order.id',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    //   required: true,
    //   show: false,
    // },
    // {
    //   label: t('图纸ID'),
    //   field: 'id',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    //   required: true,
    //   show: false,
    // },
    {
      label: t(''),
      field: 'routeList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'routeList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    record.value.modid = data.modid
    record.value.routeList = data.routeList.map(item => {
      item.bout = item.bout == '1' ? true : false;
      item.breport = item.breport == '1' ? true : false;
      item.bcheck = item.bcheck == '1' ? true : false;
      item.bmachine = item.bmachine == '1' ? true : false;
      item.bkey = item.bkey == '1' ? true : false;
      return item
    })
    record.value.__t = new Date().getTime();
    // setFieldsValue(record.value);
    setRouteDataChildTableData(record.value);
    // RouteDataChildTable.clearSelectedRowKeys()
    setDrawerProps({ loading: false });
  });

  const [registerRouteDataChildTable, routeDataChildTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRouteChildDelete.bind(this, record),
          },
          auth: 'mes:orderRoute:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showIndexColumn: false, //是否显示序列号
    // rowSelection: {
    //   type: 'radio',
    // },
  });
  function handleRouteChildDelete(record: Recordable) {
    routeDataChildTable.deleteTableDataRecord(record);
  }

  async function setRouteDataChildTableData(_res: Recordable) {
    routeDataChildTable.setColumns([
      {
        // title: t('上移 / 下移'),
        title: t('加工顺序'),
        slot: 'sortUp',
        width: 90,
      },
      // {
      //   title: t('工序'),
      //   dataIndex: 'operCode',
      //   dataLabel: 'basOper.name',
      //   width: 120,
      //   align: 'left',
      //   editRow: true,
      //   editable: true,
      //   editComponent: 'TreeSelect',
      //   editComponentProps: {
      //     api: basMesOperTreeData,
      //     params: { isShowCode: true },
      //     canSelectParent: false,
      //   },
      //   editRule: true,
      // },
      {
        title: t('工序编码'),
        dataIndex: 'operCode',
        width: 80,
        align: 'left',
      },
      {
        title: t('工序名称'),
        dataIndex: 'basOper.name',
        width: 80,
        align: 'left',
      },
      {
        title: t('关键工序'),
        dataIndex: 'bkey',
        width: 80,
        align: 'center',
        slot: 'checkBox',
      },
      {
        title: t('计价方式'),
        dataIndex: 'costType',
        width: 150,
        align: 'center',
        dictType: 'mes_price_mode',
        editRow: true,
        editable: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'mes_price_mode',
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('是否委外'),
        dataIndex: 'bout',
        width: 80,
        align: 'center',
        slot: 'checkBox',
      },
      {
        title: t('是否报工'),
        dataIndex: 'breport',
        width: 80,
        align: 'center',
        slot: 'checkBox',
      },
      {
        title: t('是否检验'),
        dataIndex: 'bcheck',
        width: 80,
        align: 'center',
        slot: 'checkBox',
      },
      {
        title: t('是否上机'),
        dataIndex: 'bmachine',
        width: 80,
        align: 'center',
        slot: 'checkBox',
      },

      // {
      //   title: t('技能标准'),
      //   dataIndex: 'techLevel',
      //   width: 150,
      //   align: 'center',
      //   dictType: 'mes_tech_level',
      //   editRow: true,
      //   editable: true,
      //   editComponent: 'Select',
      //   editComponentProps: {
      //     dictType: 'mes_tech_level',
      //     allowClear: true,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('技能控制'),
      //   dataIndex: 'techCtrl',
      //   width: 150,
      //   align: 'center',
      //   dictType: 'mes_tech_ctrl',
      //   editRow: true,
      //   editable: true,
      //   editComponent: 'Select',
      //   editComponentProps: {
      //     dictType: 'mes_tech_ctrl',
      //     allowClear: true,
      //   },
      //   editRule: false,
      // },
      {
        title: t('报工方式'),
        dataIndex: 'reportType',
        width: 150,
        align: 'center',
        dictType: 'mes_report_type',
        editRow: true,
        editable: true,
        editComponent: 'Select',
        editComponentProps: {
          dictType: 'mes_report_type',
          allowClear: true,
        },
        editRule: false,
      },
      {
        title: t('计件单价'),
        dataIndex: 'iprice',
        width: 100,
        align: 'center',
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'center',
        editRow: true,
        editable: true,
        editComponent: 'Input',
        editRule: false,
      },
    ]);
   
    routeDataChildTable.setTableData(record.value.routeList || []);
    console.log(record.value.routeList,'record.value.routeList===');
   
  }


  function clickUp(record) {
    // 上移
    let arr = routeDataChildTable.getDataSource();

    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }

    if (index === 0) {
      return false;
    }

    arr.splice(index - 1, 1, ...arr.splice(index, 1, arr[index - 1]));
    routeDataChildTable.setTableData(arr || []);
  }

  // 下移
  function clickDown(record) {
    let arr = routeDataChildTable.getDataSource();
    let index = -1;
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id == record.id) {
        index = i;
        break;
      }
    }
    if (index === arr.length - 1) {
      return false;
    }
    arr.splice(index, 1, ...arr.splice(index + 1, 1, arr[index]));
    routeDataChildTable.setTableData(arr || []);
  }

  //获取表格数据
  async function getRouteDataChildList() {
    let routeDataChildListValid = true;
    let routeDataChildList: Recordable[] = [];
    for (const record of routeDataChildTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        routeDataChildListValid = false;
      }
      routeDataChildList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of routeDataChildTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      routeDataChildList.push({
        ...record,
        status: '1',
      });
    }
    if (!routeDataChildListValid) {
      throw { errorFields: [{ name: ['routeDataChildList'] }] };
    }
    return routeDataChildList;
  }

  async function handleSubmit() {
    try {
      // const data = await validate();
      setDrawerProps({ confirmLoading: true });
      // const params: any = {
      //   isNewRecord: record.value.isNewRecord,
      //   id: record.value.id,
      // };
      const data = {}
      data.list = await getRouteDataChildList();
      data.list.forEach(item => {
        item.modid =  record.value.modid
        item.bout = item.bout ? '1' : '0';
        item.breport = item.breport ? '1' : '0';
        item.bcheck = item.bcheck ? '1' : '0';
        item.bmachine = item.bmachine ? '1' : '0';
        item.bkey = item.bkey ? '1' : '0';
      })
      const res = await mesOrderRouteSaveRoute(data);
      setDrawerProps({ confirmLoading: false });
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
  function handleBasMesRouteOperAdd() {
    routeSelectRef.value.openSelectModal();
  }


  // 工序选择
  // function handSelect(selectData) {
  //   selectData.forEach((item) => {
  //     basMesRouteOperTable.insertTableDataRecord({
  //       id: new Date().getTime(),
  //       isNewRecord: true,
  //       editable: true,
  //       operCode: item.code,
  //       basOper: { name: item.name },
  //       bkey: item.bkey,
  //       costType: item.costType,
  //       bout: item.bout,
  //       breport: item.breport,
  //       bcheck: item.bcheck,
  //       techLevel: item.techLevel,
  //       techCtrl: item.techCtrl,
  //       reportType: item.reportType,
  //     });
  //   });
  // }
  async function handSelect(selectData) {
    let arr = await routeDataChildTable.getDataSource();
    selectData.forEach((item) => {
      let flag = true;
      arr.forEach((res) => {
        if (res.operCode == item.code) {
          flag = false;
        }
      });
      if (flag) {
        routeDataChildTable.insertTableDataRecord({
          ...item,
          // id: new Date().getTime() + item.id,
          editable: true,
          isNewRecord: true,
          operCode: item.code,
          basOper: { name: item.name },
          bkey: item.bkey == '1' ? true : false,
          bout: item.bout == '1' ? true : false,
          breport: item.breport == '1' ? true : false,
          bcheck: item.bcheck == '1' ? true : false,
        });
      }
    });
  }




  function handleRouteDataChildRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }
</script>
<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
</style>